
#include "Mutex.h"

C_Mutex_Ptr
C_Mutex_New(void)
{
	int err;
	C_Mutex_Ptr p = C_Malloc(sizeof(C_Mutex));
	if (p != NULL)
	{
		err = pthread_mutex_init(&p->Handle, NULL);
		if (err != 0)
		{
			C_Free(p);
			return NULL;
		}
	}
	return p;
}

void
C_Mutex_Free(C_Mutex_Ptr p)
{
	if (p == NULL)
		return;
	pthread_mutex_destroy(&p->Handle);
	C_Free(p);
}

C_Bool_t
C_Mutex_Aquire(C_Mutex_Ptr p)
{
	int err;
	if (p == NULL)
		return C_False;
	err = pthread_mutex_lock(&p->Handle);
	return (err == 0) ? C_True : C_False;
}

void
C_Mutex_Release(C_Mutex_Ptr p)
{
	if (p != NULL)
		pthread_mutex_unlock(&p->Handle);
}



C_CondVar_Ptr
C_CondVar_New(void)
{
	C_CondVar_Ptr p = C_Malloc(sizeof(C_CondVar));
	if (p != NULL)
	{
		pthread_cond_init(&p->Handle, NULL);
	}
	return p;
}

void
C_CondVar_Free(C_CondVar_Ptr p)
{
	if (p == NULL)
		return;

	pthread_cond_destroy(&p->Handle);

	C_Free(p);
}

C_Bool_t
C_CondVar_Wait(C_CondVar_Ptr c, C_Mutex_Ptr m)
{
	int err;
	if (c == NULL || m == NULL)
		return C_False;
	err = pthread_cond_wait(&c->Handle, &m->Handle);
	return (err == 0) ? C_True : C_False;
}

C_Bool_t
C_CondVar_TimedWait(C_CondVar_Ptr c, C_Mutex_Ptr m,
		const struct timespec *ts, C_Bool_t *timedout)
{
	int err;
	if (c == NULL || m == NULL || ts == NULL || timedout == NULL)
		return C_False;

	*timedout = C_False;

	err = pthread_cond_timedwait(&c->Handle, &m->Handle, ts);

	*timedout = (err != 0) ? C_True : C_False;

	return C_True;
}

C_Bool_t
C_CondVar_Signal(C_CondVar_Ptr p)
{
	int err;
	if (p == NULL)
		return C_False;
	err = pthread_cond_signal(&p->Handle);
	return (err == 0) ? C_True : C_False;
}
